package com.yjhh.tilemap;

/**
 * @author Michael Lawrence Evans :: michael@longliveman.com
 */

import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.List;
import javax.imageio.ImageIO;

public class MapTileStitching {

    public static void main(String[] args) {
        MapTileStitching tileStitcher = new MapTileStitching();
        tileStitcher.run(args);
    }

    public void run(String[] args) {
        String sourcesPath = "E:\\map2\\13";
        File inDir = new File(sourcesPath);
        File outFile = new File(sourcesPath+"map.png");
        File[] fileList = inDir.listFiles();

        //文件名称进行排序
        List<File> folderListTemp = Arrays.asList(fileList);
        sortByFileName(folderListTemp);


        int rows = fileList.length;

        //获取列个数
        File folderOne = folderListTemp.get(0);
        int childLength = folderOne.listFiles().length;
        int cols = childLength;

        BufferedImage[][] images = new BufferedImage[rows][cols];

        try {
            for (int i = 0; i < folderListTemp.size(); i++) {
                File folder = folderListTemp.get(i);
                File[] files = folder.listFiles();

                List<File> fileListTemp = Arrays.asList(files);
                sortByFileName(fileListTemp);

                for (int j = 0; j < fileListTemp.size(); j++) {
                    File inFile = fileListTemp.get(j);
                    BufferedImage image = ImageIO.read(inFile);
                    images[i][j] = image;
                }
            }

        } catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }

        //Our map tiles are square, with dimensions of 256 by 256 pixels.  With 4 rows and 	//4 columns, we create a 1024 by 1024 image.

        BufferedImage outputImage = new BufferedImage(256 * rows, 256 * cols, BufferedImage.TYPE_INT_ARGB_PRE);
        Graphics2D g = outputImage.createGraphics();

        //Loop through the rows and columns
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                g.drawImage(images[i][j], i * 256, j * 256, 256, 256, null);
            }
        }
//        g.setColor(new Color(255,10,10,100));
//        g.fillOval(206,80,400,400);

//        g.fillRect(426,426,400,400);


        try {
            ImageIO.write(outputImage, "png", outFile);
        } catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }
    }

    private void sortByFileName(List<File> fileListTemp) {
        Collections.sort(fileListTemp, new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                if (o1.isDirectory() && o2.isFile())
                    return -1;
                if (o1.isFile() && o2.isDirectory())
                    return 1;
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

}